﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Estore.Models
{
    public class EFEstoreRepository : IEstoreRepository
    {
  
        private ASP_EstoreEntities1 db = new ASP_EstoreEntities1();
       
        public void commitchange()
        {
            db.SaveChanges();
        }
        // user
        public User ValidateUser(string loginName, string password)
        {
            return db.Users.FirstOrDefault(u => u.User_name == loginName && u.Pass_word == password);
        }
        public void addusers(User u)
        {
            db.AddToUsers(u);
        }
        public User finduserbyloginname(string loginname)
        {
            return db.Users.FirstOrDefault(u=>u.User_name==loginname);
        }
        // product
        public IQueryable<Product> FindAllProduct()
        {
            var results = from p in db.Products select p;
            return results.AsQueryable();
        }
        public IQueryable<Product> FindProductById(int id)
        {
            var results = from p in db.Products where p.Product_id ==id select p;
            return results.AsQueryable();
        }

        // category
        public IQueryable<Category> Findcategory()
        {
            var results = from c in db.Categories where c.Is_leaf == 0 select c;
            return results;
        }
        public IQueryable<Category> Findsubcategory(int id)
        {
            var results = from c in db.Categories
                          where c.Is_leaf == 1 && c.Parent_id == id
                          select new { Category = c };
            var subcate = new List<Category>();
            results.ToList().ForEach(result =>
            {
                subcate.Add(result.Category);
            });
            return subcate.AsQueryable();
        }
        public void addcategory(Category cate)
        {
            db.AddToCategories(cate);
        }
        public int test()
        {
            return 10;
        }
    }
}